package com.gmail.jaredjeya.awesomeplatformer.model.level;

import java.io.IOException;
import java.util.Random;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.gmail.jaredjeya.awesomeplatformer.Constants;
import com.gmail.jaredjeya.awesomeplatformer.model.tiles.Tile;

public class Level {

	/**
	 * 0xFF000000 = bgTile = 0<br>
	 * 0xFF0000FF = blueTile = 1<br>
	 * 0xFFFF0000 = redTile = 2<br>
	 * 0xFFFFFF00 = spawn = (sets bgTile)<br>
	 * 0xFF00FF00 = goal = 3<br><huehuehue><gib mony pls>
	 */
	private int tiles[];
	
	public int width;
	public int height;
	
	public float spawnX;
	public float spawnY;

	public float goalX;
	public float goalY;

	public Level(int width, int height) {
		createLevel(width, height);
	}

	public Level(String path, Context context) {
		try {
			Bitmap levelBitmap = BitmapFactory.decodeStream(context.getAssets().open(path));
			width = levelBitmap.getWidth();
			height = levelBitmap.getHeight();
			tiles = new int[width * height];
			for (int x = 0; x < width; x++) {
				for (int y = 0; y < height; y++) {
					switch(levelBitmap.getPixel(x, y)) {
						case 0xFF000000:
							tiles[x + y * width] = 0;
							break;
						case 0xFF0000FF:
							tiles[x + y * width] = 1;
							break;
						case 0xFFFF0000:
							tiles[x + y * width] = 2;
							break;
						case 0xFFFFFF00:
							tiles[x + y * width] = 3;
							setSpawnLocation(x + 0.5F, y + 0.5F);
							Log.v(Constants.DEBUG_TAG, x + " " + y);
							break;
						case 0xFF00FF00:
							tiles[x + y * width] = 4;
							setGoalLocation(x + 0.5F, y + 0.5F);
							break;
						default:
							tiles[x + y * width] = 0;
							break;
					}
				}
				//context.getAssets().close();
			}
		}
		catch (IOException e) {
			createLevel(8, 8);
			e.printStackTrace();
		}

	}

	private void createLevel(int width, int height) {
		tiles = new int[width * height];
		this.width = width;
		this.height = height;
		Random rand = new Random();
		for (int i = 0; i < tiles.length; i++) tiles[i] = rand.nextInt(8) == 0 ? 0 : 2;
		setSpawnLocation(0.5F, 0.5F);
	}

	public Tile getTileAt(int x, int y) {
		if (x >= width) x = width - 1;
		if (y >= height) y = height - 1;
		if (x < 0) x = 0;
		if (y < 0) y = 0;

		switch (tiles[x + y * width]) {
			case 0:
				return Tile.bg;
			case 1:
				return Tile.blue;
			case 2:
				return Tile.red;
			case 3:
				return Tile.bg;
			case 4:
				return Tile.goal;
			default:
				return Tile.red;
		}
	}

	public void setSpawnLocation(float x, float y) {
		spawnX = x;
		spawnY = y;
	}
	
	private void setGoalLocation(float x, float y) {
		goalX = x;
		goalY = y;
	}

}
